package xin.marcher.module.lifecycle.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.common.message.DataChangeMessage;
import xin.marcher.module.common.utils.JsonUtil;

import java.util.List;
import java.util.Objects;

/**
 *
 */
@Slf4j
@Component
public class ItemExpriResultInformListener implements MessageListenerConcurrently {

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                log.info("考核结果消息通知，消息内容：{}", messageExt.getBody());
                String msg = new String(messageExt.getBody());

                DataChangeMessage tableDataChangeMessage = JsonUtil.json2Object(msg, DataChangeMessage.class);
                if (Objects.isNull(tableDataChangeMessage)) {
                    throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
                }
                informByPush(tableDataChangeMessage);
            }
        } catch (Exception e) {
            log.error("consume error, 消费考核结果失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }

        return null;
    }


    /**
     * 第三方平台推送消息到运营
     * (此处模拟推送消息服务，消息平台业务商品侧不实现)
     *
     * @param message
     */
    private void informByPush(DataChangeMessage message) {
        String messageBody = "考核结果信息，"
                + "action:" + message.getAction()
                + "table:" + message.getTableName()
                + "data:" + message.getColumnValues();
        log.info("消息推送中：消息内容：{}", messageBody);
    }
}
